import Vue from 'vue'
import VueRouter from 'vue-router'
import homeChildren from './home.children'
import {decrypt} from '@/utils/crypto'
import asideMenu from '@/config/asideMenu'

Vue.use(VueRouter);

//登录路由守卫

function beforeEnter(to,from,next){
    if(localStorage.getItem('token')){
        to.path === '/' ? next('/main') : next();
    }else{
        next('/login')
    }
}

const routes = [
    {
        path:'/',
        beforeEnter
    },
    {
        path: '/login',
        name: 'login',
        meta:{
            title:'登录'
        },
        component: () => import(/* webpackChunkName: "login" */ '../views/login/index.vue')
    },
    {
        path: '/main',
        name: 'main',
        meta:{
            title:'首页'
        },
        redirect:'/main/outline',
        beforeEnter,
        component: () => import(/* webpackChunkName: "main" */ '../views/main/index.vue'),
        children:homeChildren
    }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

let writePath = ['/login','/'];  //路由白名单

//路由权限守卫
router.beforeEach((to,from,next) => {
    if(writePath.includes(to.path)){
        next();
    }else{
        if(localStorage.getItem('userinfo')){
            let userinfo = JSON.parse(decrypt(localStorage.getItem('userinfo')));
            let identity = userinfo.identity.name;  //身份

            // asideMenu  身份  to.name
            let isAuthority;

            console.log(to.name)
            asideMenu.forEach(item => {
                item.children.forEach(val => {
                    if(val.name === to.name){
                        isAuthority = val.identity.includes(identity)
                    }
                })
            })

            isAuthority ? next() : next('/login')
        }else{
            next();
        }
    }
})




export default router
